import { GraphQLError, GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';


export const RegExpScalar = new GraphQLScalarType({
  name: 'RegExp',
  description: '正则表达式类型，用于正则查询！',

  parseValue(value: string) {
    if (typeof value === 'object') {
      return value;
    }
    const regex = new RegExp(value);
    return regex; // sent to resolvers
  },

  serialize(value: string) {
    if (typeof value === 'object') {
      return value;
    }
    const regex = new RegExp(value);
    return regex; // sent to the client
  },

  parseLiteral(ast) {
    if (ast.kind !== Kind.STRING) {
      throw new GraphQLError(
        `Query error: Can only parse dates strings, got a: ${ast.kind}`,
        [ast],
      );
    }
    if (typeof ast.value === 'object') {
      return ast.value;
    }
    const regex = new RegExp(ast.value);
    return regex;
  }
});
